#!/bin/bash

if [ $# -gt 0 ] ; then
	if [[ -f "$1.h" || -f "$1.cpp" ]]; then
		echo "ERROR : A class or some files by this name already exists !";
		exit 1;
	fi
   
  sExt="cpp"
  if [[ $# -gt 1 && $2 == "c" ]]; then
    echo "File Type : C";
    sExt="c";
    exit 1;
  fi

	echo "#pragma once" >> "$1.h";
	echo -e "#ifndef ${1^^}_H" >> "$1.h"; 
	echo -e "#define ${1^^}_H\n" >> "$1.h";

	#Creating the header file with the class name
	echo -e "#include <stdlib.h>" >> "$1.h";
	echo -e "#include <iostream>\n" >> "$1.h";
	echo "class $1 {" >> "$1.h";
	echo "public:" >> "$1.h";
	echo "	$1();" >> "$1.h";
	echo "	~$1();" >> "$1.h";
	echo "};" >> "$1.h";

	echo -e "\n#endif //${1^^}_H" >> "$1.h";

	#Creating the cpp file with the default constructor and destructor
	echo -e "#include \"$1.h\"\n" >> "$1.$sExt";
	
	echo "$1::$1(){" >> "$1.$sExt";
	echo "" >> "$1.$sExt";
	echo "}" >> "$1.$sExt"

	echo "$1::~$1(){" >> "$1.$sExt";
	echo "" >> "$1.$sExt";
	echo "}" >> "$1.$sExt";

	if [ ! -f "main.$sExt" ]; then
		echo -e "#include \"$1.h\"\n" >> "main.$sExt";
		echo -e "int main(int argc, char * argv[])\n{" >> "main.$sExt";
		echo -e "\treturn 0;" >> "main.$sExt";
		echo "}" >> "main.cpp";
	fi
	if [ ! -f "makefile" ]; then
		echo -e "EXEC=main" >> "makefile";
		echo -e "SRCS=main.cpp $1.$sExt" >> "makefile";
		echo -e "\${EXEC}.o:\n	gcc \${SRCS} -lstdc++ -o \${EXEC}" >> "makefile";
		echo -e "#!/bin/bash\n\nmake -f makefile" >> "build.sh";
		chmod +x build.sh;
	else
		content=""
		while read line 
		do
			if [[ $line == *SRCS=* ]]; then
				content="$content$line $1.$sExt\n";
			else
				if [[ $line == *gcc* ]]; then
					line="\t$line";
				fi
				content="$content$line\n";
			fi
		done < makefile
		echo -e $content > makefile;
	fi
fi
